package com.example.day27_videocall_server;

import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

/**
 * Description:socket通讯 服务端
 * Created by Gdu on 2021/1/5 11:30.
 */

public class SocketLive {
    private static final String TAG = "SocketLive";
    private SocketCallback socketCallback;
    private String uriPath = "ws://192.168.18.52:40002";
    private WebSocket webSocket;

    public SocketLive(SocketCallback socketCallback) {
        this.socketCallback = socketCallback;
    }

    public void start(){
        webSocketServer.start();
    }

    public void close(){
        try {
            webSocket.close();
            webSocketServer.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendData(byte[] bytes){
        if (webSocket != null && (webSocket.isOpen())) {
            webSocket.send(bytes);
        }
    }

    private WebSocketServer webSocketServer = new WebSocketServer(new InetSocketAddress(40002)){

        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            SocketLive.this.webSocket = conn;
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            Log.i("SocketLive", "onClose======" + reason);
        }

        @Override
        public void onMessage(WebSocket conn, String message) {}

        @Override
        public void onMessage(WebSocket conn, ByteBuffer message) {
            Log.i("SocketLive", "onMessage======" + message.remaining());
            byte[] buf = new byte[message.remaining()];
            message.get(buf);
            socketCallback.CallBack(buf);
        }

        @Override
        public void onError(WebSocket conn, Exception ex) {
            Log.i("SocketLive", "onError======" + ex.toString());
        }

        @Override
        public void onStart() {

        }
    };

    public interface SocketCallback{
        void CallBack(byte[] data);

    }

}
